<?php namespace App\Http\Controllers\Api;

use App\Exceptions\FileUploadException;
use App\Exceptions\NotFoundException;
use App\Exceptions\SecurityException;
use App\Images;
use App\Services\FileManager;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class ImageController extends ApiController
{
    public function UploadImage(Guard $guard, Request $request){
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $uploadFile = $request->file('photo');

        if(!$request->hasFile('photo'))
            throw new FileUploadException(FileUploadException::UploadFail);

        if(!$uploadFile->isValid())
            throw new FileUploadException(FileUploadException::UploadFailWithError);

        $fileName = $uploadFile->getClientOriginalName();

        $fileModel = FileManager::UploadFile($uploadFile,$fileName);

        $images = new Images();
        $images->file_id = $fileModel->id;
        $images->img_name= $fileName;
        $images->img_type= $fileModel->file_type;
        $images->save();

        return $this->buildResponse(trans('api.image.upload.success'),$images);
    }

    public function getImageUrlById($id=0){

        if($id == 0)
            return \Response::download('images/default_photo.jpg','default_photo.jpg',[],'inline');

        $images = Images::find($id);

        if(!$images)
            throw new NotFoundException(NotFoundException::PhotoNotFound);

        $imageFile = $images->files;
        if(!$imageFile || $imageFile == null)
            return \Response::download('images/default_photo.jpg','default_photo.jpg',[],'inline');

        return \Response::download($imageFile->getLocalPath(),$imageFile->file_name,[],'inline');
    }

}